package com.bdqn.bookshop.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.bookshop.common.LoginPhoneConstants;
import com.bdqn.bookshop.dao.MallUserMapper;
import com.bdqn.bookshop.entity.MallUser;
import com.bdqn.bookshop.service.MallUserService;
import com.bdqn.bookshop.utils.DataGridViewResult;
import com.bdqn.bookshop.utils.MD5Util;
import com.bdqn.bookshop.utils.Result;
import com.bdqn.bookshop.vo.MallUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : 罗若然[LUO_RUO_RAN]
 * @date : 2020-07-24 16:01
 **/
@Service
@Transactional
public class MallUserServiceImpl extends ServiceImpl<MallUserMapper, MallUser> implements MallUserService {

    /**
     * 登录
     * @param mallUser
     * @param kaptcha
     * @param sysCaptcha
     * @return
     * @throws Exception
     */
    @Override
    public Result<MallUser> LoginUsers(MallUser mallUser, String kaptcha, String sysCaptcha) throws Exception {
        if (StringUtils.isBlank(kaptcha)||StringUtils.isBlank(sysCaptcha)||!sysCaptcha.equalsIgnoreCase(kaptcha)){
            return Result.createError("验证码错误");
        }
        //加密
        String md5 = MD5Util.MD5Encode(mallUser.getPassword(), "UTF-8");
        mallUser.setPassword(md5);
        QueryWrapper<MallUser> queryWrapper=new QueryWrapper<MallUser>();
        String vaEmail="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        if (mallUser.getUserName().matches(vaEmail)){
            queryWrapper.eq( "email",mallUser.getUserName());
        }else {
            queryWrapper.eq( "user_Name",mallUser.getUserName());
        }
        queryWrapper.eq("password",mallUser.getPassword());
        mallUser=baseMapper.selectOne(queryWrapper);
        if (mallUser!=null){
            if (mallUser.getIsLocked()!=2){ //1是账号未锁定 2是锁定了账号无法登陆的是 不等于2就是可以登录
                return Result.createSuccess(baseMapper.selectOne(queryWrapper),"登录成功");
            }
            return Result.createError(mallUser,"此账户已锁定，无法使用");
        }
        return Result.createError(mallUser,"登录失败密码或者用户名有误");
    }


    /**
     * 注册
     * @param mallUser
     * @param repassword
     * @return
     */
    @Override
    public Result registerUser(MallUser mallUser, String repassword) {
        //这段代码是用来判断
        if (!mallUser.getPassword().equals(repassword)){
            return    Result.createError("输入密码和确认密码不一致,请重新输入");
        }

        //判断注册用户名是否存在
        QueryWrapper<MallUser> queryWrapper=new QueryWrapper<MallUser>();

            queryWrapper.eq("user_Name",mallUser.getUserName());
        MallUser mallUsers=baseMapper.selectOne(queryWrapper);
        if (mallUsers!=null){
            return  Result.createError("用户名已存在请重新输入");
        }


        //邮箱正则
        String vaEmail="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        if (!mallUser.getEmail().matches(vaEmail)){
            return  Result.createError("邮箱形式有误，请以@邮箱形式注册");
        }

        //用户名正则
        String vaUserName="^[a-za-z][a-za-z0-9]{5,8}$";
        if (!mallUser.getUserName().matches(vaUserName)){
            return  Result.createError("请以字母开头组合数字6~8位,首位不能出现_");
        }


        //手机号码正则
        String vaphones="^[1][3,4,5,7,8][0-9]{9}$";
        if (!mallUser.getPhone().matches(vaphones)){
            return  Result.createError("联系电话输入需要11位，输入有误请重新输入");
        }

        //判断密码长度的6到12位
        String vaRegex="^[0-9]{6,18}$";
        if (!mallUser.getPassword().matches(vaRegex)){
            return  Result.createError("密码长度必须要6~12位,清重新输入");
        }

        //加密
        String md5 = MD5Util.MD5Encode(mallUser.getPassword(), "UTF-8");
        mallUser.setPassword(md5);
        mallUser.setCreateTime(new Date());
        mallUser.setIsLocked(1);
        int num=baseMapper.insert(mallUser);
        if (num>0){
            return   Result.createSuccess(num,"添加成功");
        }
        return  Result.createError(num,"添加失败");
    }

    /**
     * 修改密码
     * @param
     * @return
     */
    @Override
    public Result updatePassWord(Integer id,String password,String newPassword,String repassword) {

        String vaRegex="^[0-9]{6,18}$";
        if (!newPassword.matches(vaRegex)){
            return  Result.createError("密码长度必须要6~12位,清重新输入");
        }

        if (!newPassword.equals(repassword)){
            return Result.createError("新密码和确认密码不一致请重新输入");
        }




        String passwords = MD5Util.MD5Encode(password, "UTF-8");
        String newPwd = MD5Util.MD5Encode(newPassword, "UTF-8");
        QueryWrapper<MallUser> queryWrapper=new QueryWrapper<MallUser>();
        queryWrapper.eq("id",id);
        queryWrapper.eq("password",passwords);
        //用密码去查询是否有查询到数据
        MallUser mallUser=baseMapper.selectOne(queryWrapper);



        //判断是否有数据
        if (mallUser!=null){
            mallUser.setPassword(newPwd);
            int num=baseMapper.updateById(mallUser);
            if (num>0){
                return Result.createSuccess(mallUser,"密码修改成功");
            }
                 return Result.createError(mallUser,"密码修改失败");
        }
        return Result.createError(mallUser,"原密码有误,请重新输入");
    }

    /**
     * 个人信息
     * @param id
     * @param mallUser
     * @return
     */
    @Override
    public Result updateInfo(Integer id, MallUser mallUser) {
        QueryWrapper<MallUser> queryWrapper=new QueryWrapper<MallUser>();
        queryWrapper.eq("id",id);
         MallUser mallUsers=baseMapper.selectOne(queryWrapper);

        //邮箱正则
        String vaEmail="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        if (!mallUser.getEmail().matches(vaEmail)){
            return  Result.createError("邮箱形式有误，请以@邮箱形式注册");
        }

        //手机号码正则
        String vaphones="^[1][3,4,5,7,8][0-9]{9}$";
        if (!mallUser.getPhone().matches(vaphones)){
            return  Result.createError("联系电话输入需要11位，输入有误请重新输入");
        }
        if (mallUsers!=null){
            mallUsers.setNickName(mallUser.getNickName());
            mallUsers.setEmail(mallUser.getEmail());
            mallUsers.setPhone(mallUser.getPhone());

            int num=baseMapper.updateById(mallUsers);
            if (num>0){
                return Result.createSuccess(mallUsers,"信息修改成功");
            }
                return Result.createError(mallUsers,"信息修改失败");
        }
                return Result.createError(mallUsers,"服务器异常。。。");
    }


    @Override
    public DataGridViewResult mallUserList(MallUserVo mallUserVo) {
        IPage<MallUser> page = new Page<>(mallUserVo.getPage(),mallUserVo.getLimit());
        QueryWrapper<MallUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(mallUserVo.getUserName()),"user_name",mallUserVo.getUserName());
        queryWrapper.like(StringUtils.isNotBlank(mallUserVo.getNickName()),"nick_name",mallUserVo.getNickName());
        queryWrapper.eq(mallUserVo.getIsLocked()!=null,"islocked",mallUserVo.getIsLocked());
        queryWrapper.ge(mallUserVo.getStartTime()!=null,"create_time",mallUserVo.getStartTime());
        queryWrapper.le(mallUserVo.getEndTime()!=null,"create_time",mallUserVo.getEndTime());
        baseMapper.selectPage(page,queryWrapper);
        return new DataGridViewResult(page.getTotal(),page.getRecords());
    }

    @Override
    public Result batchLocked(String ids, String bool) {
        String [] idArr = ids.split(",");
        try {
            for (String id : idArr) {
                MallUser mallUser = new MallUser();
                mallUser.setId(Integer.valueOf(id));
                if (bool.equals("true")){
                    mallUser.setIsLocked(2);
                }else{
                    mallUser.setIsLocked(1);
                }
                baseMapper.updateById(mallUser);
            }
            return Result.createSuccess("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createError("修改失败");
        }

    }

    @Override
    public Result editById(MallUser mallUser) {
        UpdateWrapper<MallUser> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq(mallUser.getId() != null, "id", mallUser.getId());
        userUpdateWrapper.eq(mallUser.getIsLocked() != null, "islocked", mallUser.getIsLocked());
        if(baseMapper.updateById(mallUser)>0){
            return Result.createSuccess("修改成功");
        }
        return Result.createError("修改失败");
    }




        @Override
        public Map<String, Object> SmsVerification(String phone) {
            Map<String, Object> map = new HashMap<>();
            try {
                LoginPhoneConstants.SendSmsResponse(phone);
                map.put("code", 200);
                map.put("msg", "短信验证发送成功");
                map.put("success",true);
                return map;
            } catch (ClientException e) {
                map.put("code", 300);
                map.put("msg", e.getMessage());
                map.put("error",false);
                return map;

            }
        }
    }